import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import {FilterItem} from 'components'
import {
    Form,
    Button,
    Row,
    Col,
    Divider,
    Input
} from 'antd'

const FormItem = Form.Item

const filterStyle = {
    style: {
        marginBottom: 16
    }
}
const Filter = ({
    filterItems,
    onFilterChange,
    form: {
        getFieldDecorator,
        getFieldsValue,
        setFieldsValue
    }
}) => {
    const handleFields = (fields) => {
        // const {createTime} = fields if (createTime.length) {     fields.createTime =
        // [         createTime[0].format('YYYY-MM-DD'),
        // createTime[1].format('YYYY-MM-DD')     ] }
        return fields
    }

    const handleSubmit = () => {
        let fields = getFieldsValue()
        fields = handleFields(fields)
        onFilterChange(fields)
    }

    const handleReset = () => {
        const fields = getFieldsValue()
        for (let item in fields) {
            if ({}.hasOwnProperty.call(fields, item)) {
                if (fields[item]instanceof Array) {
                    fields[item] = []
                } else {
                    fields[item] = undefined
                }
            }
        }
        setFieldsValue(fields)
        handleSubmit()
    }

    const handleChange = (key, values) => {
        let fields = getFieldsValue()
        fields[key] = values
        fields = handleFields(fields)
        onFilterChange(fields)
    }

    const getFilterItemCol = (filterItems) => {
        const result = filterItems.map((filterItem, index) => <Col key={index} span={4}>
            <FormItem>
                {filterItem.type === 'text' && getFieldDecorator(`${filterItem.id}`, {})(<Input placeholder={filterItem.placeholder}/>)}
            </FormItem>
        </Col>);
        return ((result));
    }

    const filterItemCols = getFilterItemCol(filterItems);
    return (
        <Row gutter={24} {...filterStyle}>
            {filterItemCols}
            <Col span={6}>
                <Button type="primary" onClick={handleSubmit}>查询</Button>
                <Divider type="vertical"/>
                <Button type="ghost" onClick={handleReset}>重置</Button>
            </Col>
        </Row>
    )
}

Filter.propTypes = {
    form: PropTypes.object,
    filter: PropTypes.object,
    onFilterChange: PropTypes.func
}

export default Form.create()(Filter)
